<template>
  <p-card :bordered="false">
    <div v-if="tags">
      <div class="table-page-search-wrapper">
        <p-form layout="inline" @keyup.enter.native="searchQuery">
          <p-row :gutter="24">
            <p-col :xl="6" :lg="7" :md="8" :sm="24">
              <p-form-item label="产品编码">
                <p-input
                  placeholder="请输入"
                  v-model="queryParam.mcode"
                ></p-input>
              </p-form-item>
            </p-col>
            <p-col :xl="6" :lg="7" :md="8" :sm="24">
              <p-form-item label="产品名称">
                <p-input
                  placeholder="请输入"
                  v-model="queryParam.mname"
                ></p-input>
              </p-form-item>
            </p-col>
            <template v-if="toggleSearchStatus">
              <p-col :xl="6" :lg="7" :md="8" :sm="24">
                <p-form-item label="工艺路线编码">
                  <p-input
                    placeholder="请输入"
                    v-model="queryParam.routerCode"
                  ></p-input>
                </p-form-item>
              </p-col>
            </template>
            <p-col :xl="6" :lg="7" :md="8" :sm="24">
              <span
                style="float: left; overflow: hidden"
                class="table-page-search-submitButtons"
              >
                <p-button type="primary" @click="searchQuery" icon="search"
                  >查询</p-button
                >
                <p-button
                  type="primary"
                  @click="searchReset"
                  icon="reload"
                  style="margin-left: 8px"
                  >重置</p-button
                >
                <a @click="handleToggleSearch" style="margin-left: 8px">
                  {{ toggleSearchStatus ? "收起" : "展开" }}
                  <p-icon :type="toggleSearchStatus ? 'up' : 'down'" />
                </a>
              </span>
            </p-col>
          </p-row>
        </p-form>
      </div>
      <div class="table-operator">
        <p-button @click="addFix" type="primary" icon="plus">新增</p-button>
        <p-radio-group :value="size" @change="handleSizeChange">
          <p-radio-button value="0">送修中</p-radio-button>
          <p-radio-button value="1">待维修</p-radio-button>
          <p-radio-button value="3">维修完成</p-radio-button>
          <p-radio-button value="4">关闭</p-radio-button>
        </p-radio-group>
        <div style="float: right">
          <p-button type="primary">送修交接</p-button>
          <p-button type="primary">良品交接</p-button>
        </div>
        <template
          v-if="cgButtonList && cgButtonList.length > 0"
          v-for="(item, index) in cgButtonList"
        >
          <p-button
            v-if="
              item.optType == 'js' &&
              (item.groupTag == null || item.groupTag == '')
            "
            :key="'cgbtn' + index"
            @click="cgButtonJsHandler(item.buttonCode)"
            type="primary"
            :icon="item.buttonIcon"
            >{{ item.buttonName }}</p-button
          >
          <p-button
            v-else-if="
              item.optType == 'action' &&
              (item.groupTag == null || item.groupTag == '')
            "
            :key="'cgbtn' + index"
            @click="cgButtonActionHandler(item.buttonCode)"
            type="primary"
            :icon="item.buttonIcon"
            >{{ item.buttonName }}</p-button
          >
        </template>

        <!-- 高级查询区域 -->
        <!-- <j-super-query
        :fieldList="fieldList"
        ref="superQueryModal"
        @handleSuperQuery="handleSuperQuery"
      ></j-super-query> -->

        <p-dropdown v-for="(item, index) in groupTag" :key="index">
          <p-button>
            {{ item.name }}
            <p-icon type="down" />
          </p-button>
          <p-menu slot="overlay">
            <template v-for="(items, indexs) in item.data">
              <p-menu-item
                v-if="items.optType == 'js'"
                :key="indexs"
                @click="cgButtonJsHandler(items.buttonCode)"
              >
                <p-icon :type="items.buttonIcon" />
                {{ items.buttonName }}
              </p-menu-item>
              <p-menu-item
                v-else-if="items.optType == 'action'"
                :key="indexs"
                @click="cgButtonActionHandler(items.buttonCode)"
              >
                <p-icon :type="items.buttonIcon" />
                {{ items.buttonName }}
              </p-menu-item>
            </template>
          </p-menu>
        </p-dropdown>
        <p-dropdown v-if="selectedRowKeys.length > 0">
          <p-menu slot="overlay">
            <p-menu-item key="1" @click="batchDel">
              <p-icon type="delete" />删除
            </p-menu-item>
          </p-menu>
          <p-button style="margin-left: 8px">
            批量操作
            <p-icon type="down" />
          </p-button>
        </p-dropdown>
      </div>
      <div>
        <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
          <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
          <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
          >项
          <a style="margin-left: 24px" @click="onClearSelected">清空</a>

          <span style="float: right">
            <a @click="handleExportXls('标签模板维护')">
              <p-icon type="download" />导出
            </a>
            <p-divider type="vertical" />
            <a @click="loadData()"> <p-icon type="sync" />刷新 </a>
            <p-divider type="vertical" />
            <p-popover
              title="自定义列"
              trigger="click"
              placement="leftBottom"
              :overlay-style="getWidth"
            >
              <template slot="content">
                <p-checkbox-group
                  @change="onColSettingsChange"
                  v-model="settingColumns"
                  :defaultValue="settingColumns"
                >
                  <p-row>
                    <template v-for="item in defColumns">
                      <template
                        v-if="
                          item.key != 'rowIndex' && item.dataIndex != 'action'
                        "
                      >
                        <p-col :span="12">
                          <p-checkbox :value="item.dataIndex">{{
                            item.title
                          }}</p-checkbox>
                        </p-col>
                      </template>
                    </template>
                  </p-row>
                </p-checkbox-group>
              </template>
              <a> <p-icon type="setting" />自定义列 </a>
            </p-popover>
          </span>
        </div>

        <p-table
          ref="table"
          size="middle"
          bordered
          rowKey="id"
          :columns="columns"
          :scroll="tableScroll"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          :rowSelection="{
            selectedRowKeys: selectedRowKeys,
            onChange: onSelectChange,
          }"
          @change="handleTableChange"
        >
          <template slot="statusRemark" slot-scope="text">
            <p-tag v-if="text" color="#4064E9"
              ><p-icon type="clock-circle" />{{ text }}</p-tag
            >
          </template>
          <template slot="status" slot-scope="text">
            <p-tag v-if="text === 0" color="blue">{{
              text === 0 ? "送修中" : ""
            }}</p-tag>
            <p-tag v-if="text === 1" color="red">{{
              text === 1 ? "待维修" : ""
            }}</p-tag>
            <p-tag v-if="text === 2" color="#f50">{{
              text === 2 ? "待工艺协助" : ""
            }}</p-tag>
            <p-tag v-if="text === 3" color="green">{{
              text === 3 ? "维修完成" : ""
            }}</p-tag>
            <p-tag v-if="text === 4" color="purple">{{
              text === 4 ? "关闭" : ""
            }}</p-tag>
          </template>
          <template slot="routerCode" slot-scope="text, record">
            <a @click="routerCodeClick(record)" class="routerCode">{{
              record.routerCode
            }}</a>
          </template>
          <template slot="upload" slot-scope="text, record">
            <a @click="handleExportXls(record)">下载</a>
          </template>
          <template slot="routerPt" slot-scope="text">
            {{
              text == 1
                ? "发行"
                : text == 2
                ? "审核中"
                : text == 3
                ? "待审核"
                : "被驳回"
            }}
          </template>

          <span slot="action" slot-scope="text, record">
            <a @click="handleEdit(record)">编辑</a>
            <p-divider type="vertical" />
            <p-popconfirm
              title="确定删除吗?"
              @confirm="() => handleDelete(record.id)"
            >
              <a>删除</a>
            </p-popconfirm>
          </span>
        </p-table>
      </div>
      
    </div>
    <add-module v-else :tags.sync="tags"></add-module>
  </p-card>
</template>

<script>
import { JeecgListMixin } from "@/mixins/JeecgListMixin";
import { api } from "@/api/manage";
import JSuperQuery from "@/components/jeecg/JSuperQuery.vue";
import { filterObj, timestampToDatetime } from "@/utils/util";
import Vue from "vue";
import {
  initDictOptions,
  filterMultiDictText,
} from "@/components/dict/JDictSelectUtil";
import ButtonExpHandler from "@/components/jeecgbiz/modules/ButtonExpHandler";
import { postAction, getAction, deleteAction } from "@/api/manage";
import AddModule from "./modules/addModule";
//高级查询modal需要参数
const superQueryFieldList = [
  {
    value: "mcode",
    text: "产品编码 ",
    type: "string",
  },
  {
    value: "mname",
    text: "产品名称",
    type: "string",
  },
  {
    value: "productLine",
    text: "产品系列",
    type: "string",
  },
  {
    value: "routerCode",
    text: "工艺路线编码",
    type: "string",
  },
  {
    value: "processName",
    text: "工艺路线名称",
    type: "string",
  },
  {
    value: "processType",
    text: "工艺路线类型",
    type: "string",
  },
];

export default {
  name: "MesBcTemplateList",
  mixins: [JeecgListMixin],
  components: {
    JSuperQuery,
    AddModule,
  },
  data() {
    return {
      fieldList: superQueryFieldList,
      cgButtonLinkList: [],
      title: "", //存表名
      EnhanceJS: "",
      cgButtonList: [],
      groupTag: [],
      queryInfo: [],
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
      approveModal: false,
      approveLoading: false,
      curRow: null,
      approveFormModel: {
        modifyDesc: "", // 修改说明
        modifyGist: "", // 修改依据
      },
      approveformRules: {
        modifyDesc: [
          { required: true, message: "请输入内容", trigger: "blur" },
        ],
        modifyGist: [
          { required: true, message: "请输入内容", trigger: "blur" },
        ],
      },
      code: "",
      tags: true,
      // 表头
      columns: [],
      //列设置
      settingColumns: [],
      //列定义
      defColumns: [
        {
          title: "序号",
          dataIndex: "",
          key: "rowIndex",
          width: 60,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          },
        },
        {
          title: "单据单号",
          align: "center",
          dataIndex: "receiptNumber",
        },
        {
          title: "送修日期 ",
          align: "center",
          dataIndex: "sendRepairDateParam",
          customRender: function (text) {
            return timestampToDatetime(text);
          },
        },
        {
          title: "送修线体",
          align: "center",
          dataIndex: "linename",
        },
        {
          title: "生产工单",
          align: "center",
          dataIndex: "productionBillno",
          //   scopedSlots: { customRender: "routerCode" },
        },
        {
          title: "工序工单",
          align: "center",
          dataIndex: "processBillno",
        },
        {
          title: "SN/PN",
          align: "center",
          dataIndex: "snPn",
        },
        {
          title: "优先级",
          align: "center",
          dataIndex: "priority",
        },
        {
          title: "产品编码",
          align: "center",
          dataIndex: "mcode",
        },
        {
          title: "产品名称",
          align: "center",
          dataIndex: "mname",
        },
        {
          title: "状态",
          align: "center",
          dataIndex: "status",
          scopedSlots: { customRender: "status" },
        },
        {
          title: "状态备注",
          align: "center",
          dataIndex: "statusRemark",
          scopedSlots: { customRender: "statusRemark" },
        },
        {
          title: "操作",
          dataIndex: "action",
          align: "center",
          width: 130,
          fixed: "right",
          scopedSlots: { customRender: "action" },
        },
      ],
      url: {
        list: "/mes-manufacture/mfOnlineRepairTask/list",
        delete: "/mes-manufacture/mfOnlineRepairTask",
        deleteBatch: "/mes-craft/craft/mesPeProcessRoute/deleteBatch",
        exportXlsUrl: "/mes-code/mesBcTemplate/export",
        getColumns: "/mes-code/online/cgform/api/getColumns/",
        buttonAction: "/mes-code/online/cgform/api/doButton",
      },
      dictOptions: {},
      size: "0",
    };
  },
  computed: {
    importExcelUrl: function () {
      return `${api.test}${this.url.importExcelUrl}`;
    },
    getWidth: function () {
      if (this.defColumns.length > 14) {
        return { width: "500px" };
      }
    },
    tableScroll: function () {
      if (this.columns.length > 13) {
        return { x: this.columns.length * 150 - 450, y: 400 };
      } else {
        return { y: 450 };
      }
    },
  },
  created() {
    this.initColumns();
  },
  mounted() {},
  methods: {
    loadData(arg) {
      if (!this.url || !this.url.list) {
        console.log("请设置url.list属性!");
        return;
      }
      // 加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      var params = this.getQueryParams(); // 查询条件
      this.loading = true;
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = res.data.records;
          this.dataSource.map((item) => {
            item.routerStatus = item.routerStatus == 1 ? true : false;
          });
          console.log(this.dataSource);
          this.ipagination.total = res.data.total;
        }
        if (res.code === 510) {
          this.$message.warning(res.msg);
        }
        this.$nextTick(() => {
          this.loading = false;
        });
      });
    },
    handleCancel() {
      this.approveModal = false;
      this.$refs.approveForm.resetFields();
    },
    addFix() {
      this.tags = false;
    },
    handleSizeChange(e) {
      this.size = e.target.value;
      this.loadData();
    },
    routerCodeClick(row) {
      this.editRoute(row, "1");
    },
    handledownload() {
      console.log("下载");
    },
    getQueryParams() {
      // 获取查询条件
      const sqp = {};
      if (this.superQueryParams) {
        sqp["superQueryParams"] = encodeURI(this.superQueryParams);
      }
      var param = Object.assign(
        sqp,
        this.queryParam,
        this.isorter,
        this.filters
      );
      param.field = this.getQueryField();
      param.pageNo = this.ipagination.current;
      param.limit = this.ipagination.pageSize;
      param.status = this.size;
      return filterObj(param);
    },
    initColumns() {
      var key = this.$route.name + ":colsettings";
      let colSettings = Vue.ls.get(key);
      if (colSettings == null || colSettings == undefined) {
        let allSettingColumns = [];
        this.defColumns.forEach(function (item, i, array) {
          allSettingColumns.push(item.dataIndex);
        });
        this.settingColumns = allSettingColumns;
        this.columns = this.defColumns;
      } else {
        this.settingColumns = colSettings;
        const cols = this.defColumns.filter((item) => {
          if (item.key == "rowIndex" || item.dataIndex == "action") {
            return true;
          }
          if (colSettings.includes(item.dataIndex)) {
            return true;
          }
          return false;
        });
        this.columns = cols;
      }
    },
    //列设置更改事件
    onColSettingsChange(checkedValues) {
      var key = this.$route.name + ":colsettings";
      Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000);
      this.settingColumns = checkedValues;
      const cols = this.defColumns.filter((item) => {
        if (item.key == "rowIndex" || item.dataIndex == "action") {
          return true;
        }
        if (this.settingColumns.includes(item.dataIndex)) {
          return true;
        }
        return false;
      });
      this.columns = cols;
    },

    //高级查询方法
    handleSuperQuery(arg) {
      if (!arg) {
        this.superQueryParams = "";
        this.superQueryFlag = false;
      } else {
        this.superQueryFlag = true;
        this.superQueryParams = JSON.stringify(arg);
      }
      this.loadData();
    },
    initDictConfig() {},
    // 弹出窗组件
    showDemoModal() {
      this.$refs.modalCompon.modalShow();
    },
    //筛选分组
    getGroupTag(arrList) {
      let arr = [];
      var map = {},
        dest = [];
      arrList.forEach((item, index) => {
        if (item.groupTag) {
          arr.push(item);
        }
      });
      for (var i = 0; i < arr.length; i++) {
        var ai = arr[i];
        if (!map[ai.groupTag]) {
          dest.push({
            groupTag: ai.groupTag,
            name: ai.groupName,
            data: [ai],
          });
          map[ai.groupTag] = ai;
        } else {
          for (var j = 0; j < dest.length; j++) {
            var dj = dest[j];
            if (dj.groupTag == ai.groupTag) {
              dj.data.push(ai);
              break;
            }
          }
        }
      }
      this.groupTag = dest;
      console.log(dest);
    },
    showLinkButton(item, record) {
      let btn = new ButtonExpHandler(item.exp, record);
      return btn.show;
    },
    initCgEnhanceJs(enhanceJs) {
      if (enhanceJs) {
        let Obj = eval("(" + enhanceJs + ")");
        this.EnhanceJS = new Obj(getAction, postAction, deleteAction);
        this.cgButtonJsHandler("created");
      } else {
        this.EnhanceJS = "";
      }
    },
    initCgButtonList(btnList) {
      let linkArr = [];
      let buttonArr = [];
      if (btnList && btnList.length > 0) {
        for (let i = 0; i < btnList.length; i++) {
          let temp = btnList[i];
          if (temp.buttonStyle == "button") {
            buttonArr.push(temp);
          } else if (temp.buttonStyle == "link") {
            linkArr.push(temp);
          }
        }
      }
      this.cgButtonLinkList = [...linkArr];
      this.cgButtonList = [...buttonArr];
      console.log("链接增强", this.cgButtonLinkList);
    },
    cgButtonJsHandler(buttonCode) {
      if (this.EnhanceJS[buttonCode]) {
        this.EnhanceJS[buttonCode](this);
      }
    },
    cgButtonActionHandler(buttonCode) {
      //处理自定义button的 需要配置该button自定义sql
      if (!this.selectedRowKeys || this.selectedRowKeys.length == 0) {
        this.$message.warning("请先选中一条记录");
        return false;
      }
      if (this.selectedRowKeys.length > 1) {
        this.$message.warning("请只选中一条记录");
        return false;
      }
      let params = {
        formId: this.code,
        buttonCode: buttonCode,
        dataId: this.selectedRowKeys[0],
      };
      console.log("自定义按钮请求后台参数：", params);
      postAction(this.url.buttonAction, params).then((res) => {
        if (res.success) {
          this.loadData();
          this.$message.success("处理完成!");
        } else {
          this.$message.warning("处理失败!");
        }
      });
    },
    cgButtonLinkHandler(record, buttonCode, optType) {
      if (optType == "js") {
        if (this.EnhanceJS[buttonCode]) {
          this.EnhanceJS[buttonCode](this, record);
        }
      } else if (optType == "action") {
        let params = {
          formId: this.code,
          buttonCode: buttonCode,
          dataId: record.id,
        };
        console.log("自定义按钮link请求后台参数：", params);
        postAction(this.url.buttonAction, params).then((res) => {
          if (res.success) {
            this.loadData();
            this.$message.success("处理完成!");
          } else {
            this.$message.warning("处理失败!");
          }
        });
      }
    },
    batchDel: function () {
      if (!this.url.deleteBatch) {
        this.$message.error("请设置url.deleteBatch属性!");
        return;
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一条记录！");
      } else {
        var ids = "";
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ",";
        }
        var that = this;
        this.$confirm({
          title: "确认删除",
          content: "是否删除选中数据?",
          onOk: function () {
            that.loading = true;
            deleteAction(that.url.deleteBatch + `/${ids}`, {})
              .then((res) => {
                if (res.success) {
                  that.$message.success(res.msg);
                  that.loadData();
                  that.onClearSelected();
                } else {
                  that.$message.warning(res.msg);
                }
              })
              .finally(() => {
                that.loading = false;
              });
          },
        });
      }
    },
  },
};
</script>
<style scoped>
</style>